package cn.zyjblogs.nio;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileChannel03 {
    public static void main(String[] args) {

        //创建文件的输入流
        try(FileInputStream fileInputStream = new FileInputStream(NIOFileChannel03.class.getClassLoader().getResource("1.txt").getFile());
            FileOutputStream fileOutputStream = new FileOutputStream("2.txt")) {
            FileChannel fileInputChannel = fileInputStream.getChannel();

            FileChannel FileOutputchannel = fileOutputStream.getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(512);

            while (true){
                //重要的操作 清空和复位buffer 如果clear会死循环
                buffer.clear();
                int read = fileInputChannel.read(buffer);
                System.out.println("read: "+read);
                if (read ==-1){
                    //读取结束
                    break;
                }
                buffer.flip();
                FileOutputchannel.write(buffer);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
